package com.lzy.crm.util;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import redis.clients.jedis.JedisPubSub;

import com.alibaba.fastjson.JSONObject;
import com.lzy.crm.domain.PpUser;
import com.lzy.crm.service.PpUserService;

public class RedisMsgPubSubListener extends JedisPubSub {
	private static final Log logger = LogFactory
			.getLog(RedisMsgPubSubListener.class);

	@Resource
	private PpUserService pUserService;

	@Override
	public void onMessage(String channel, String message) {
		// TODO Auto-generated method stub
		logger.debug("onMessage channel:" + channel + "; message :" + message);

		try {
			if (message == null || message.equals("")) {
				logger.error("message is null");
				return;
			}

			JSONObject json = JSONObject.parseObject(message);

			int uid = json.getIntValue("uid");
			int cash_num = json.getIntValue("cash_num");

			PpUser user = pUserService.getById(uid);
			if (user != null) {
				user.setRoomcard(cash_num);
				pUserService.updateByPrimaryKeySelective(user);
			} else {
				logger.error("PpUser is null :" + message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onPMessage(String pattern, String channel, String message) {
		// TODO Auto-generated method stub
		logger.debug("onPMessage channel:" + channel + "; message :" + message);
	}

	@Override
	public void onSubscribe(String channel, int subscribedChannels) {
		// TODO Auto-generated method stub
		logger.debug("onSubscribe channel:" + channel
				+ "; subscribedChannels :" + subscribedChannels);
	}

	@Override
	public void onUnsubscribe(String channel, int subscribedChannels) {
		// TODO Auto-generated method stub
		logger.debug("onUnsubscribe channel:" + channel
				+ "; subscribedChannels :" + subscribedChannels);
	}

	@Override
	public void onPUnsubscribe(String pattern, int subscribedChannels) {
		// TODO Auto-generated method stub
		logger.debug("onPUnsubscribe pattern:" + pattern
				+ "; subscribedChannels :" + subscribedChannels);
	}

	@Override
	public void onPSubscribe(String pattern, int subscribedChannels) {
		// TODO Auto-generated method stub
		logger.debug("onPSubscribe pattern:" + pattern
				+ "; subscribedChannels :" + subscribedChannels);
	}

}
